package com.learn.rocketmq.simple;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;

/**
 * 消费者
 *
 * @date 2021/8/16
 */
public class Consumer {

    private final String consumerGroupName;
    private final String nameServer;
    private final String topicName;

    private DefaultMQPushConsumer consumer;
    private final MessageListenerConcurrently messageListener;

    public Consumer(String consumerGroupName, String nameServer, String topicName, MessageListenerConcurrently messageListener) {
        this.consumerGroupName = consumerGroupName;
        this.nameServer = nameServer;
        this.topicName = topicName;
        this.messageListener = messageListener;
    }

    public DefaultMQPushConsumer getConsumer() {
        return consumer;
    }

    public void init() throws MQClientException {
        // 创建一个消息消费者，并设置一个消息消费者组
        consumer = new DefaultMQPushConsumer(consumerGroupName);
        // 指定 NameServer 地址
        consumer.setNamesrvAddr(nameServer);
        // 设置 Consumer 第一次启动是从队列头部开始消费还是队列尾部开始消费
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);

        // 订阅指定 Topic 下的所有消息
        consumer.subscribe(topicName, "*");

        // 注册消息监听器
        consumer.registerMessageListener(messageListener);

        // 消费者对象在使用之前必须要调用 start 初始化
        consumer.start();
    }

    public void destroy() {
        // 销毁
        consumer.shutdown();
    }
}
